import 'dart:ffi';
import 'dart:io';

import 'package:bottom_drawer/bottom_drawer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gameplay_flutter/generated/assets.dart';
import 'package:gameplay_flutter/lib_baseview/widget/dialogs.dart';
import 'package:gameplay_flutter/lib_runtime/extension/widget/widget_wrapper.dart';
import 'package:gameplay_flutter/m_main/main_page_model.dart';
import 'package:image_picker/image_picker.dart';
import 'package:ones/ui.dart';
import 'package:provider/provider.dart';

import '../../../resource/language/generated/l10n.dart';


GlobalKey<_DrawerAddRoom> DrawerAddRoomKey = GlobalKey();
class DrawerAddRoom extends StatefulWidget {
  final controller;
  const DrawerAddRoom({ required Key key,required this.controller, }) : super(key: key);
  @override
  _DrawerAddRoom createState() => _DrawerAddRoom();
}

class _DrawerAddRoom extends State<DrawerAddRoom> {
  int selectIndex = -1;
  final double _headerHeight = 60.0;
  final BottomDrawerController _controller = BottomDrawerController();
  late List<String> tagsList = ['Singing','Game','Love','Family','Girls','Boys','Gossip'];
  late int tagsIndex = 0;
  final TextEditingController nameController = TextEditingController();
  final TextEditingController introductionController = TextEditingController();
  final ImagePicker _picker = ImagePicker();
  late String imagePath = 'http://habibifile1.oss-cn-hangzhou.aliyuncs.com/2025/common/headImg/104.png';
  File? imageLocalPath;
  bool isOpen = false;

  @override
  void initState() {
    super.initState();
  }


  void open(){
    setState(() {
      isOpen = true;
    });
    _controller.open();
  }

  @override
  void dispose() {
    super.dispose();
  }

  void close(){
    _controller.close();
    setState(() {
      isOpen = false;
      imageLocalPath = null;
      imagePath = 'http://habibifile1.oss-cn-hangzhou.aliyuncs.com/2025/common/headImg/104.png';
      nameController.text = '';
      introductionController.text = '';
      tagsIndex = 0;
    });
  }

  Future<void> getImage() async {
    try {
      final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
      if (image != null) {
        // 处理选择的图片
        File imageFile = File(image.path);
       var imageUrl = await widget.controller.uploadImage(image);
        setState(() {
          imageLocalPath = imageFile;
          imagePath = imageUrl[0];
        });
       // if(imageUrl != false){
       //   setState(() {
       //
       //   });
       // }
      }
    } catch (e) {
      print('${T.current.h2_picture_err}: $e');
      // 显示错误提示
    }
  }

  @override
  Widget build(BuildContext context) {
    return _buildBottomDrawer(context);
  }

  Widget _buildBottomDrawer(BuildContext context) {
    final navBarProvider = Provider.of<MainPageModel>(context);
    return BottomDrawer(
      followTheBody: false,
      header: _buildBottomDrawerHead(context,navBarProvider),
      body: _buildBottomDrawerBody(context,navBarProvider),
      headerHeight: _headerHeight,
      drawerHeight: 1050,
      color: isOpen? Colors.black.withOpacity(.15): Colors.transparent,
      controller: _controller,
      callback: (val){
        if(!val){
          navBarProvider.changeBottomState(true);
        }
      },
      boxShadow: const [
          BoxShadow(
          color: Colors.transparent,
          blurRadius: 10,
          spreadRadius: 5,
          offset: const Offset(2, -1), // changes position of shadow
        ),
      ],
    );
  }

  Widget _buildBottomDrawerHead(BuildContext context,navBarProvider) {
    return Column(
      children: [
        InkWell(
          onTap: (){
            close();
            navBarProvider.changeBottomState(true);
          },
          child:  SizedBox(
              width: MediaQuery.sizeOf(context).width,
              height: 220
          ),
        ),
        Container(
          height: _headerHeight,
          decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.vertical(top: Radius.circular(15))
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const  SizedBox(width: 10,),
              const Image(image: AssetImage(Assets.homeCancel),width: 12,height: 12,).onTap((){
                close();
                navBarProvider.changeBottomState(true);
              }),
              Expanded(
                  child: Center(
                    child: Container(
                      transform: Matrix4.translationValues(-15, 0, 0),
                      child: Text(T.current.h1_enjoy_room_1,style: const TextStyle(
                          fontSize: 18
                      ),),
                    )
                  )
              )
            ],
          ),
        )
      ],
    );
  }

  Widget _buildBottomDrawerBody(BuildContext context,navBarProvider) {
    return  SizedBox(
      width: double.infinity,
      height: 620.0,
      child: SingleChildScrollView(
        child: _buildButtons(navBarProvider),
      ),
    );
  }

  Widget _buildButtons(navBarProvider) {
    return  Container(
      height: 630.0,
      decoration: const BoxDecoration(
        color: Colors.white
      ),
      child: Column(
        children: [
          Container(
            decoration: const BoxDecoration(
                color: Colors.white,
                image: DecorationImage(
                    image: AssetImage(Assets.homeMineAddBg),
                    fit: BoxFit.fill
                )
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                  SizedBox(
                    width: MediaQuery.sizeOf(context).width*.3,
                    height: 110.h,
                    child: Stack(
                      children: [
                        Positioned(
                            left: MediaQuery.sizeOf(context).width*.3 - 100,
                            top: 0,
                            child: Container(
                                width:73.w,
                                height: 73.h,
                                // padding:const EdgeInsets.symmetric(horizontal: 10,vertical: 5),
                                margin: const EdgeInsets.only(top: 10),
                                decoration: const BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.all(Radius.circular(8))
                                ),
                                child:ClipRRect(
                                  borderRadius: BorderRadius.circular(8),
                                  child: imageLocalPath != null?Image.file(
                                    imageLocalPath!,
                                    fit: BoxFit.cover,
                                  ) : Image.network(imagePath,fit: BoxFit.fill,),
                                )
                            )
                        ),
                         Positioned(
                            left: MediaQuery.sizeOf(context).width*.3 - 48,
                            top: 60,
                            child: Image(image: AssetImage(Assets.homeMineAddAvatar),width: 36,height: 36,)
                        ),
                      ],
                    ),
                ).onTap((){
                  getImage();
                  }),
                Padding(
                  padding: EdgeInsets.all(20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(T.current.h2_creat_room_name).fontSize(16).fontWeight(FontWeight.bold),
                      TextField(
                        controller: nameController,
                        decoration: InputDecoration(
                            border: InputBorder.none, // 去掉边框
                            hintText: T.current.h2_creat_room_name_p,
                            contentPadding: EdgeInsets.symmetric(vertical: 8),
                            hintStyle: const TextStyle(
                                color: Color(0xffc1c1c1)
                            )// 提示文本
                        ),
                      ),
                      Text(T.current.h2_creat_room_introduction).fontSize(16).fontWeight(FontWeight.bold),
                      TextField(
                        controller: introductionController,
                        decoration: InputDecoration(
                            border: InputBorder.none, // 去掉边框
                            hintText: T.current.h2_creat_room_introduction_p,
                            contentPadding: const EdgeInsets.symmetric(vertical: 8),
                            hintStyle: const TextStyle(
                                color: Color(0xffc1c1c1)
                            )// 提示文本
                        ),
                      ),
                      Text(T.current.h2_creat_room_theme).fontSize(16).fontWeight(FontWeight.bold),
                      SizedBox(height: 10,),
                      SizedBox(
                        width: MediaQuery.sizeOf(context).width,
                        height: 80.h,
                        child: Wrap(
                          direction: Axis.horizontal,
                          spacing: 10,
                          // 行间距
                          runSpacing: 10,
                          children: List.generate(widget.controller.roomTagsList.value.length > 0? widget.controller.roomTagsList.value.length- 1 : 0, (index) => getItem(index)),
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
          Center(
            child:  Container(
              height: 50,
              decoration: BoxDecoration(
                gradient:const LinearGradient(
                  colors: [Color(0xff8A72FE), Color(0xff6549EC)],
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                ),
                borderRadius: BorderRadius.circular(40.0),
              ),
              child: ElevatedButton(
                onPressed:  () async{
                  if(nameController.text.isEmpty){
                    showToast(T.current.h2_creat_room_name_p);
                    return;
                  }
                  if(introductionController.text.isEmpty){
                    showToast(T.current.h2_creat_room_introduction_p);
                    return;
                  }
                 var state = await widget.controller.createRoom(imagePath,nameController.text,widget.controller.roomTagsList.value[tagsIndex].roomCategoryIds,introductionController.text,context);
                 if(state){
                   setState(() {
                     imageLocalPath = null;
                     imagePath = 'http://habibifile1.oss-cn-hangzhou.aliyuncs.com/2025/common/headImg/104.png';
                     nameController.text = '';
                     introductionController.text = '';
                     tagsIndex = 0;
                   });
                   close();
                   widget.controller.loadMineData(1,widget.controller.roomTypesList.value[1].type,'refresh',1); //int fetchType, int roomType,refresh,pageNum
                   navBarProvider.changeBottomState(true);
                 }
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.transparent, // 设置按钮背景为透明
                  shadowColor: Colors.transparent, // 去掉阴影
                  padding:const EdgeInsets.symmetric(horizontal: 45.0, vertical: 0),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8.0),
                  ),
                ),
                child: Text(T.current.h2_creat_room_title).color(Colors.white).fontSize(18),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget getItem(int index){
    bool isChoose = tagsIndex == index;
    var list = widget.controller.roomTagsList.value.sublist(1);
    return Container(
      padding:const EdgeInsets.symmetric(horizontal: 14,vertical: 6),
      decoration: BoxDecoration(
        color: isChoose ? Colors.white : const Color(0xffF8F6FF),
        borderRadius:const BorderRadius.all(Radius.circular(30)),
        border: Border.all(color: isChoose ?const Color(0xff8A72FE) : Colors.transparent)
      ),
      child: Text(list[index].roomCategoryName).color(isChoose ?const Color(0xff8A72FE) : Color(0xffCBB1DF)).fontWeight(isChoose?FontWeight.bold:null),
    ).onTap((){
      setState(() {
        tagsIndex = index;
      });
    });
  }


}